import React from 'react';
import { connect } from 'react-redux';
import * as routeActions from 'react-router-redux';
import { routeMenuConfig, RouteMenuKey } from 'Constants/routeMenuConfig';
import './index.scss';

class RouteMenu extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      selectedKey: RouteMenuKey.HOME,
    };

    this.clickHandle = ::this.clickHandle;
    this.generatorMenu = ::this.generatorMenu;
  }
  componentWillMount() {
    const { locationBeforeTransitions } = this.props;
    const navPath = locationBeforeTransitions.pathname.split('/');
    navPath.shift();
    this.setState({ selectedKey: navPath[0] });
  }
  clickHandle(key) {
    const { dispatch } = this.props;
    if (key !== this.state.selectedKey) {
      this.setState({ selectedKey: key }, () => {
        dispatch(routeActions.push(key));
      });
    }
  }
  generatorMenu() {
    const { selectedKey } = this.state;
    return (
      routeMenuConfig.map(item => (
        <div className="menu-item" key={item.route}>
          <div
            className={`content-wrap ${selectedKey === item.route ? 'menu-active' : 'menu-normal'}`}
            onClick={this.clickHandle.bind(this, item.route)}
          >
            <img src={item.icon} alt="" />
            <div className="label">{item.name}</div>
          </div>
        </div>
      ))
    );
  }
  render() {
    return (
      <div className="v-route-menu">
        { this.generatorMenu() }
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { ...state.routing };
}

export default connect(mapStateToProps)(RouteMenu);
